package cn.lk1234.imt.utils;

import java.util.Date;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CommonUtils {

	public static String getNowStr() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(new Date());
	}

	public static String getNowStr(String formatType) {
		SimpleDateFormat format = new SimpleDateFormat(formatType);
		return format.format(new Date());
	}

	/**
	 * 判断字符串是否为null或""
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNotNull(Object str) {
		boolean r = false;
		if (str != null) {
			if (str.getClass().getName().equals("java.lang.String")) {
				if (str != null && String.valueOf(str).trim().length() > 0) {
					r = true;
				}
			} else {
				r = true;
			}
		}
		return r;
	}

	// 方法二：通过类加载目录getClassLoader()加载属性文件
	public static String getValueByKey(String key) {
		String result = "";

		// 方法二：通过类加载目录getClassLoader()加载属性文件
		InputStream in = CommonUtils.class.getClassLoader().getResourceAsStream("common.properties");
		// InputStream in =
		// this.getClass().getClassLoader().getResourceAsStream("mailServer.properties");

		// 注：Object.class.getResourceAsStream在action中调用报错，在普通java工程中可用
		// InputStream in =
		// Object.class.getResourceAsStream("/mailServer.properties");
		Properties prop = new Properties();
		try {
			prop.load(in);
			result = prop.getProperty(key).trim();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	// 下载excel文件
	public static boolean downLoadFile(HttpServletRequest request, HttpServletResponse response, String fileName,
			File file) throws Exception {
		// 设置输出的格式
		response.reset();
		// 根据浏览器设置下载文件名的编码
		if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
			fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
		} else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
			// fileName = URLEncoder.encode(fileName, "UTF-8");
			fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
		} else {
			// fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
			fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
		}
		response.setContentType("application/xls;charset=GBK");
		// 设置下载文件头
		response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
		response.setHeader("Connection", "close");
		// 设置文件长度
		int fileLeng = Integer.parseInt(file.length() + "");
		response.setContentLength(fileLeng);

		byte[] buffer = new byte[4096];// 缓冲区
		BufferedOutputStream output = null;
		BufferedInputStream input = null;
		try {
			input = new BufferedInputStream(new FileInputStream(file));
			output = new BufferedOutputStream(response.getOutputStream());
			int n = -1;
			// 遍历，开始下载
			while ((n = input.read(buffer, 0, 4096)) > -1) {
				output.write(buffer, 0, n);
			}
			output.flush(); // 不可少
			response.flushBuffer();// 不可少
		} catch (Exception e) {
			// 异常捕捉
			e.printStackTrace();
		} finally {
			// 关闭流，不可少
			if (input != null)
				input.close();
			if (output != null)
				output.close();
			file.delete();
		}
		return false;
	}

	/**
	 * 使用ArrayList处理，如果是自己定义的类，则要合理重写equals方法
	 * 
	 * @param a
	 * @return
	 */
	public static <T> int getMostFrequentByArrayList(T a[]) {
		if (a == null || a.length == 0) {
			return 0;
		}
		int size = a.length;
		int result = 0;
		// 持有所有集合的集合。指定容量以免扩容带来的性能消耗，不过可能浪费空间
		ArrayList<ArrayList<T>> severalTempList = new ArrayList<ArrayList<T>>(size);

		for (int i = 0; i < size; i++) {
			boolean isAdd = false;
			T t = a[i];
			// 遍历severalTempList每个ArrayList，找到t所属的则添加上去
			for (int j = 0; j < severalTempList.size(); j++) {
				ArrayList<T> singleTemps = severalTempList.get(j);
				if (singleTemps != null) {
					if (t.equals(singleTemps.get(0))) {
						singleTemps.add(t);
						isAdd = true;
					}
				}
			}
			// 找不到t所属的则创建新的ArrayList添加到severalTempList，并将t添加到新的ArrayList
			if (!isAdd) {
				ArrayList<T> singleTemps = new ArrayList<T>();
				singleTemps.add(t);
				severalTempList.add(singleTemps);
			}
		}

		// 经过拆分后长度最大的集合
		ArrayList<T> largestList = severalTempList.get(0);
		// 从索引为1开始就可以了
		for (int i = 1; i < severalTempList.size(); i++) {
			// 通过遍历找到元素最多的集合
			if (severalTempList.get(i).size() > largestList.size()) {
				largestList = severalTempList.get(i);
			}

			result = largestList.size();
		}

		return result;

	}

	// 时间格式
	public static String changeTimeFormat(String str_input, String format) {
		String time = "";
		if (str_input != null) {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmm");
			sdf.setLenient(false);
			try {
				time = sdf.format(sdf2.parse("20090909" + str_input));
			} catch (Exception e) {
				return time;
			}
			return time;
		}
		return time;
	}

	public static String genId(int len) {
		Random random = new Random(System.currentTimeMillis());
		String sRand = "";
		for (int i = 0; i < len; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
		}
		return sRand;
	}

}
